package com.demo.controller;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.anji.captcha.model.common.ResponseModel;
import com.anji.captcha.model.vo.CaptchaVO;
import com.anji.captcha.service.CaptchaService;
import com.demo.model.MsgModel;
import com.demo.service.MsgService;
import com.demo.tool.ResultUtil;

import cn.hutool.extra.servlet.ServletUtil;

@Controller
public class IndexController {
	@Autowired
	private MsgService msgSer;
	
	@Autowired
	private CaptchaService captchaService;
	
	@Value("${ipMsgMaxCount}")
	private int ipMsgMaxCount;
	
	@RequestMapping("/")
    public String index(){
       return "index";
    }
	

	@PostMapping(value = "send_msg")
	@ResponseBody
	public ResultUtil sendMsg(CaptchaVO captchaVO,String phone,HttpServletRequest request) {
		
		ResponseModel response = captchaService.verification(captchaVO);
	    if(response.isSuccess() == false){
	    	return new ResultUtil(0, "验证码错误");
	    }
		
		int random = (int) ((Math.random() * 9 + 1) * 100000);
        String msgInfo="验证码为："+random+",10分钟内有效。请勿告诉他人。";
		//TODO 对接短信平台

		MsgModel msg=new MsgModel();
		msg.setPhone(phone);
		msg.setInfo(msgInfo);
		
		
		// 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 定义时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 格式化当前时间
        msg.setTime(now.format(formatter));
		//获取IP
        msg.setIp(ServletUtil.getClientIP(request));
        
		
		
		//验证同一手机号60秒内只能发送一次
        int coun1=msgSer.getCount1(msg);
        System.out.println("coun1:"+coun1);
        if(coun1!=0) {
        	return new ResultUtil(0, "同一手机号60秒内只能发送一次");
        }
        
		//验证同一IP3秒内只能发送一次
        int coun2=msgSer.getCount2(msg);
        System.out.println("coun2:"+coun2);
        if(coun2!=0) {
        	return new ResultUtil(0, "同一IP3秒内只能发送一次");
        }
        
		//验证同一IP每天最多发送条数
        int coun3=msgSer.getCount3(msg);
        System.out.println("coun3:"+coun3);
        if(coun3>=ipMsgMaxCount) {
        	//短信审计:按天记录个ip发送短信的数量，对超过阈值的进行记录并预警(发短信)
        	System.out.println("触发预警");

        	return new ResultUtil(0, "同一IP每天最多发送"+ipMsgMaxCount+"条");
        }

		//TODO 对接短信接 口


        msgSer.insert(msg);
        
        return new ResultUtil(1, "发送成功"); 
		
	}
}
